/**
 * @Author @fiber-cloud
 * @Date 2025/8/24 9:40
 * 抢占式执行
 */

class Counter{
    public int count = 0;

    public void add(){
        count++;
    }
}
public class ThreadDemo4 {

    public static void main(String[] args) {
        Counter counter = new Counter();
        //整两个线程，两个线程分别针对counter调用5w次的add方法

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 500000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 500000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();

        //等待线程结束
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //打印最终的counter值
        System.out.println("counter= "+counter.count);
    }
}
